package login;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CreateAccountServlet
 */
@WebServlet("/CreateAccountServlet")
public class CreateAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateAccountServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Integer userID = 0;
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
       // String confPassword = request.getParameter("confirmpassword");
        String firstName = request.getParameter("fname");
        String lastName = request.getParameter("lname");
        String phoneNumber = request.getParameter("phone");
        String emailAddress = request.getParameter("email");

        String checkUser = "select * from login where UserName='" + userName + "'";


       // userID = stmt.executeUpdate(createUser, Statement.RETURN_GENERATED_KEYS);

        try {
            Class.forName("com.mysql.jdbc.Driver");
        }
        catch (ClassNotFoundException e) {
            System.out.println(e.getMessage());
        }
        try {
            Connection con = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/defect_tracker","root", "root");
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(checkUser);
            boolean isUser = rs.next();
            if (isUser) {
                // redirect to create page as username already in use

                response.sendRedirect("CreateAccount.jsp?error=unexist&UserName="  + userName + "&FName=" + firstName + "&LName=" + lastName + "&Email=" + emailAddress + "&Phone=" + phoneNumber);
            }
            else
            {
            	String createUser = "insert into user (FName, LName, Email, Phone) values ( '"  + firstName + "','" + lastName
                 		 + "','" + emailAddress  + "','" + phoneNumber  + "')" ;
               stmt.executeUpdate(createUser, Statement.RETURN_GENERATED_KEYS);

            	 ResultSet getKey = stmt.getGeneratedKeys();
            	 if (getKey.next()) {
            		    userID = getKey.getInt(1);
            	} else {
            		 System.out.println("An error has occured");
            	}
            	 String createLogin = "insert into login (UserID, UserName, UserPassword) values ( "  + userID + ",'" + userName
                		 + "','" + password  + "')" ;

            	stmt.executeUpdate(createLogin);

            	HttpSession session = request.getSession(true);
                session.setAttribute("FirstName",firstName);
                session.setAttribute("LastName", lastName);
                session.setAttribute("UserID", userID);
                session.setAttribute("UserName", userName);

                // redirect to success page
                response.sendRedirect("LoginSuccess.jsp");
            }
        }
        catch (SQLException e) {
            System.out.println("SQLException occured: " + e.getMessage());
            e.printStackTrace();
        }
    }

}
